<script setup lang="ts">
import {getImagesApi} from "@/api/common/file";

/**
 * 使用方法: <x-image-select v-model="addForm.avatar"/>
 * 暂时弃用!!
 */
const defaultSrc = 'http://localhost:3000/api/public/images/avatar/avatar_105.jpg'
const props = withDefaults(defineProps<{
  modelValue: string | null
}>(), {modelValue: defaultSrc})
const emit = defineEmits(['update:modelValue'])

const value = computed({
  get() {
    return props.modelValue || defaultSrc
  },
  set(value) {
    emit('update:modelValue', value)
  }
})
// 图片list
const list: Ref<string[]> = ref([])
// 图片列表是否可见
const photoListVisible = ref(false)
// 选中图片index
const selectedIndex = ref(-1)

function setListVisible() {
  photoListVisible.value = !photoListVisible.value
}

function selectPhoto(item: string, index: number) {
  value.value = item
  selectedIndex.value = index
}

// 获取所有的头像src
async function getAllAvatarSrc() {
  list.value = await getImagesApi('avatar')
}

onMounted(async () => {
  // await getAllAvatarSrc()
})
</script>

<template>
  <div class="select flex flex-items-center">
    <el-image crossorigin="anonymous" class="select__image photo photo--large" :src="value" @click="setListVisible">
      <template #error>
        <el-image class="photo"
                  @click="setListVisible"
                  :src="defaultSrc"></el-image>
      </template>
    </el-image>
    <el-text size="small">(点击左边头像来选择
      <el-text size="small" v-if="photoListVisible">,下滑可看到更多头像</el-text>
      <el-text size="small">)</el-text>
    </el-text>
  </div>
  <div class="list" v-if="photoListVisible">
    <el-image
        crossorigin="anonymous"
        v-for="(item,index) in list"
        :key="index"
        :src="item"
        @click="selectPhoto(item,index)"
        class="photo"
        :class="{'selected-border-style':selectedIndex === index}"
    >
    </el-image>
  </div>
</template>

<style scoped lang="scss">
.list {
  height: 11em;
  display: flex;
  flex-wrap: wrap;
  overflow: scroll;
}

.photo {
  width: 4em;
  margin: 0.4em;
  border-radius: 0.5em;
  cursor: pointer;
}

.photo--large {
  font-size: 1.2em;
}

.select__image {
  &:hover {
    opacity: 0.3;
  }
}

.select__text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 0.8em;
}

.selected-border-style {
  box-shadow: 2px 2px 10px rgb(39, 83, 125),
  4px 4px 10px rgba(0, 0, 0, 0.3);
  transform: scale(1.08);

}

</style>